package com.polarrose.wsf.validator;

import java.util.ArrayList;
import java.util.List;

public class CollectionElementsValidator implements Validator<List>
{
    private Validator<Object> elementValidator;    

    public void validate(List list)
        throws ValidatorException
    {
        List<String> validationErrors = new ArrayList<String>();

        for (int i = 0; i < list.size(); i++) {
            try {
                elementValidator.validate(list.get(i));
            } catch (ValidatorException e) {
                validationErrors.add("Element #" + i + " is invalid: " + e.getMessage());
            }
        }

        if (!validationErrors.isEmpty()) {
            throw new ValidatorException(validationErrors);
        }
    }

    public void setElementValidator(String clazz)
    {
        try {
            elementValidator = (Validator<Object>) Class.forName(clazz).newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Could not instantiate collection element validator.", e);
        }
    }    
}
